import Foundation
import Combine
class SpeedViewModel: ObservableObject {
    @Published var downloadSpeed: Double = 0.0
    @Published var uploadSpeed: Double = 0.0 // 新增存储上传速度的属性
    @Published var currentTestPhase: TestPhase = .none

    private var ndt7Test: NDT7Test?

    func startTest(isDownload: Bool) {
        downloadSpeed = 0.0
        uploadSpeed = 0.0
        currentTestPhase = isDownload ? .download : .upload
        isDownload ? startDownloadTest() : startUploadTest()
    }

    private func startDownloadTest() {
        runTest(download: true, upload: false) { [weak self] error in
            self?.handleTestCompletion(error: error, phase: .download)
            print("Download test started")
        }
    }

    private func startUploadTest() {
        runTest(download: false, upload: true) { [weak self] error in
            self?.handleTestCompletion(error: error, phase: .upload)
            print("Upload test started")
        }
    }

    private func runTest(download: Bool, upload: Bool, completion: @escaping (Error?) -> Void) {
        let settings = NDT7Settings()
        ndt7Test = NDT7Test(settings: settings)
        ndt7Test?.delegate = self
        ndt7Test?.startTest(download: download, upload: upload, completion)
    }

    private func handleTestCompletion(error: Error?, phase: TestPhase) {
        if let error = error {
            print("Error during \(phase) test: \(error.localizedDescription)")
            currentTestPhase = .none
        } else {
            print("\(phase) test finished.")
            currentTestPhase = .finished
        }
    }

    func cancelTest() {
        self.downloadSpeed = 0.0
        self.uploadSpeed = 0.0
        ndt7Test?.cancel()
        currentTestPhase = .none
    }
}

extension SpeedViewModel: NDT7TestInteraction {
    func test(kind: NDT7TestConstants.Kind, running: Bool) {}

    func measurement(origin: NDT7TestConstants.Origin, kind: NDT7TestConstants.Kind, measurement: NDT7Measurement) {
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            let speed = self.calculateSpeed(numBytes: measurement.appInfo?.numBytes, elapsedTime: measurement.appInfo?.elapsedTime)
            
            if kind == .download {
                if speed > 0{
                    self.downloadSpeed = speed
                }
               
            } else if kind == .upload {
                if speed > 0{
                    self.uploadSpeed = speed // 更新上传速度
                }
            }
        }
    }

    private func calculateSpeed(numBytes: Int64?, elapsedTime: Int64?) -> Double {
        guard let numBytes = numBytes, let elapsedTime = elapsedTime else { return 0.0 }
        let bits = Double(numBytes) * 8
        let elapsedTimeInSeconds = Double(elapsedTime) / 1_000_000
        return bits / max(elapsedTimeInSeconds, 1e-6) / 1_000_000 // Convert to Mbps
    }

    func error(kind: NDT7TestConstants.Kind, error: NSError) {
        print("Error during test: \(error.localizedDescription)")
    }
}

enum TestPhase {
    case none
    case download
    case upload
    case finished
}
